/// <reference path="../vswd-ext_2.2.js" />
/*!
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
function showChooser(config) {
	var mystore;
	var result;
	var dataView;
	var pagesize = 15
	var day = new Date();
	var today = day.getFullYear() + '-' + padLeft((day.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(day.getDate().toString(), "0", 2);
	var yyday = addDays(day, -1);
	var yestoday = yyday.getFullYear() + '-' + padLeft((yyday.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(yyday.getDate().toString(), "0", 2);

	//load trackname
	var trackerstore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: 'HandlerSearchTrackerName'
		}),
		reader: new Ext.data.JsonReader({
			fields: [{ name: 'trackname'}],
			root: "data"
		})
	});

	trackerstore.load()
	var trackNameCombo = new Ext.form.ComboBox({
		id: 'trackname',
		store: trackerstore,
		mode: 'local',
		displayField: 'trackname',
		width: 130,
		valueField: 'trackname'
	});


	var fromDateEditor = new Ext.form.DateField({
		renderer: Ext.util.Format.dateRenderer('Y-m-d'),
		format: 'Y-m-d',
		value: today
	});


	var fromTimeEditor = new Ext.form.TimeField({
		value:"00:00",
		format: 'H:i',
		width: 70
	});

	var toDateEditor = new Ext.form.DateField({
		renderer: Ext.util.Format.dateRenderer('Y-m-d'),
		format: 'Y-m-d',
		value: today
	});

	var toTimeEditor = new Ext.form.TimeField({
		value: "23:59",
		format: 'H:i',
		width: 70
	});

	var tbar = new Ext.Toolbar({
		items: [_Alarm_TrackerName + ':',
		trackNameCombo,
		{
			xtype: 'tbseparator', width: 5
		},
		_Alarm_FromTime + ':',
		fromDateEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		fromTimeEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		_Alarm_ToTime + ':',
		toDateEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		toTimeEditor,
		//{xtype:'tbfill'},
		{
		tooltip: { text: _TrackerMain_Search, autoHide: true },
		icon: 'Content/images/search16.gif',
		handler: function() {
			mystore.load({
				params: {
					start: 0,
					limit: pagesize,
					trackName: trackNameCombo.getRawValue(),
					fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
					totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value
				}
			});
		}
	}, {
		tooltip: { text: _TrackerMain_Download, autoHide: true },
		icon: 'Content/images/download-zip.gif',
		handler: function() {
			if (!Ext.fly('picturesdownload')) {
				var frm = document.createElement('form');
				frm.id = 'picturesdownload';
				frm.name = id;
				frm.style.display = 'none';
				document.body.appendChild(frm);
			}
			Ext.Ajax.request({
				url: 'HandlerImageZip',
				form: Ext.fly('picturesdownload'),
				method: 'POST',
				params: {
					start: 0,
					limit: 600,
					trackName: trackNameCombo.getRawValue(),
					fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
					totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value
				},
				isUpload: true
			});

		}
	}, {
		tooltip: { text: _TrackerMain_Remove, autoHide: true },
		iconCls: 'remove-icon',
		handler: function() {
			var count = dataView.getSelectionCount();
			if (count == 0) {
				Ext.Msg.alert(_PictureResource_Tips, _PictureResource_NoChoose);
			}
			else {
				var nodes = "";
				for (var i = 0; i < count; i++) {
					if (i == 0)
						nodes += dataView.getSelectedNodes()[0].lang
					else
						nodes += "," + dataView.getSelectedNodes()[i].lang;
				}

				Ext.Msg.show({ title: _PictureResource_Tips, msg: _PictureResource_DeleteTips,
					buttons: {
						yes: _PictureResource_Yes,
						no: _PictureResource_No
					},
					fn: function(button) {
						if (button == "yes") {
							Ext.MessageBox.show({
								msg: _PictureResource_Deleting + "...",
								progress: true,
								progressText: _PictureResource_Deleting + '...',
								width: 300,
								wait: true,
								waitConfig: {
									interval: 100,
									duration: 1000,
									fn: function() {
										Ext.Ajax.request({
											url: "HandlerDeletePictures",
											params: {
												ids: nodes
											},
											callback: function(options, success, response) {
												if (success) {
													Ext.Msg.show({
														title: _PictureResource_Tips,
														msg: _PictureResource_DeleteSuccess,
														buttons: Ext.MessageBox.OK,
														icon: Ext.MessageBox.INFO,
														fn: function() {
															mystore.reload();
														}
													});
												}
												else {
													Ext.Msg.show({
														title: _PictureResource_Tips,
														msg: _PictureResource_Deletefailed,
														buttons: Ext.MessageBox.OK,
														icon: Ext.MessageBox.WARNING
													});
												}
											}
										});

										Ext.MessageBox.hide();
									}
								},
								closable: true
							});
						}
					}
				});

			}
		}
}]
	});

	var ImageChooser = function(config) {
		this.config = config;
	}

	ImageChooser.prototype = {
		// cache data by image name for easy lookup
		lookup: {},
		show: function(el, callback) {
			if (!this.win) {
				this.initTemplates();
				this.store = new Ext.data.JsonStore({
					root: 'data',
					totalProperty: "totalCount",
					proxy: new Ext.data.HttpProxy({
						url: this.config.url,
						timeout: 6000,
						method: 'GET'
					}),
					fields: [
						'name', 'sid', 'time', 'latitude', 'longitude', 'trackername', 'imgid'
					],
					listeners: {
						scope: this,
						single: true,
						'load': {
							fn: function() {
								this.view.select(0);
							}
						},
						'exception': function(mic) {
							debugger;
						}
					}
				});
				mystore = this.store;

				var formatSize = function(data) {
					if (data.size < 1024) {
						return data.size + " bytes";
					} else {
						return (Math.round(((data.size * 10) / 1024)) / 10) + " KB";
					}
				};

				var formatData = function(data) {
					data.shortName = data.name.ellipse(15);
					data.sizeString = formatSize(data);
					data.dateString = new Date(data.lastmod).format("m/d/Y g:i a");
					this.lookup[data.name] = data;
					return data;
				};

				this.view = new Ext.DataView({
					height: 390,
					//				width:650,
					tpl: this.thumbTemplate,
					multiSelect: true,
					plugins: [
						new Ext.DataView.DragSelector(), new Ext.DataView.LabelEditor()
					],
					overClass: 'x-view-over',
					itemSelector: 'div.thumb-wrap',
					emptyText: '<div style="padding:10px;">' + _PictureResource_NoData + '</div>',
					store: this.store,
					listeners: {
						'selectionchange': { fn: this.showDetails, scope: this, buffer: 100 },
						'dblclick': { fn: this.doubleClick, scope: this },
						'loadexception': { fn: this.onLoadException, scope: this },
						'beforeselect': { fn: function(view) {
							return view.store.getRange().length > 0;
						}
						},
						contextmenu: this.rightClick
					},
					prepareData: formatData.createDelegate(this)
				});
				mystore.on('beforeload', function(store) {
					mystore.baseParams = {
						start: 'start',
						limit: 'limit',
						trackName: trackNameCombo.getRawValue(),
						fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
						totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value
					}
				})
				var cfg = {
					id: 'img-chooser-dlg',
					layout: 'border',
					modal: false,
					border: false,
					plain: true,
					minimizable: true,
					iconCls: 'report-photo',
					title: _TrackerMain_PhotoReport,
					closeAction: 'close',
					items: [{
						id: 'img-chooser-view',
						region: 'center',
						autoScroll: true,
						items: this.view,
						width: 850,
						tbar: tbar
					}, {
						id: 'img-detail-panel',
						region: 'east',
						width: 350
}],
						bbar: new Ext.PagingToolbar({
							pageSize: pagesize,
							store: this.store,
							beforePageText: _Alarm_Page,
							refreshTex: _Alarm_Refresh,
							displayMsg: _Alarm_Displaying,
							emptyMsg: _Alarm_Alarm_emptyMsg,
							displayInfo: true
						})
						,
						keys: {
							key: 27, // Esc key
							handler: function() { this.win.hide(); },
							scope: this
						}
					};
					Ext.apply(cfg, this.config);
					this.win = new Ext.Window(cfg);

					this.win.on('minimize', function() {
						addTaskButtonForWindow(this);
					});
					
					this.win.on('close',function(){
						chooser = null;
					});
				}

				//this.reset();
				this.win.show(el);
				this.callback = callback;
				this.animateTarget = el;
				dataView = this.view;
			},

			initTemplates: function() {
				this.thumbTemplate = new Ext.XTemplate(
					'<tpl for=".">',
						'<div class="thumb-wrap" lang="{imgid}" id="{name}" >',
						'<div class="thumb"><img src="HandlerGetPicture?id={imgid}" title="{name}"></div>',
						'<span>{trackername}</span><span>{time}</span><span>{name}</span></div>',
					'</tpl>'
				);
				this.thumbTemplate.compile();

				this.detailsTemplate = new Ext.XTemplate(
					'<div class="details">',
						'<tpl for=".">',
							'<div class="thumb1"><img src="HandlerGetPicture?id={imgid}" title="{name}"></div><div class="details-info">',
							'<b>' + _PictureResource_Name + ':</b>',
							'<span>{trackername}</span>',
							'<b>' + _PictureResource_CaptureTime + ':</b>',
							'<span>{time}</span>',
							'<b>' + _PictureResource_PictureName + ':</b>',
							'<span>{name}</span></div>',
						'</tpl>',
					'</div>'
				);
				this.detailsTemplate.compile();
			},

			showDetails: function() {
				var selNode = this.view.getSelectedNodes();
				var detailEl = Ext.getCmp('img-detail-panel').body;
				if (selNode && selNode.length > 0) {
					selNode = selNode[0];
					//Ext.getCmp('ok-btn').enable();
					var data = this.lookup[selNode.id];
					detailEl.hide();
					this.detailsTemplate.overwrite(detailEl, data);
					detailEl.slideIn('l', { stopFx: true, duration: .2 });
				} else {
					// Ext.getCmp('ok-btn').disable();
					detailEl.update('');
				}
			},

			//	filter : function(){
			//		var filter = Ext.getCmp('filter');
			//		this.view.store.filter('name', filter.getValue());
			//		this.view.select(0);
			//	},

			//	sortImages : function(){
			//		var v = Ext.getCmp('sortSelect').getValue();
			//		this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
			//		this.view.select(0);
			//	},

			//	reset : function(){
			//		if(this.win.rendered){
			//			Ext.getCmp('filter').reset();
			//			this.view.getEl().dom.scrollTop = 0;
			//		}
			//		this.view.store.clearFilter();
			//		this.view.select(0);
			//	},

			doubleClick: function() {
				var count = dataView.getSelectionCount();
				for (var i = 0; i < count; i++) {
					var selNode = dataView.getSelectedNodes()[i];
					new Ext.Window({
						title: selNode.id,
						autoScroll: true,
						//										layout: 'fit',
						width: 660,
						height: 520,
						plain: true,
						html: "<img src='HandlerGetPicture?id=" + selNode.lang + "'></img>"

					}).show();
				}
			},
			rightClick: function(dataView, index, node, e) {
				var count = dataView.getSelectionCount();
				if (count <= 1)
					dataView.select(index);
				if (!dataView.menu) {

					dataView.menu = new Ext.menu.Menu({

						id: 'tree-ctx',

						items: [{

							text: _PictureResource_CheckPicture,

							iconCls: 'see-icon',
							handler: function() {

								var count = dataView.getSelectionCount();
								for (var i = 0; i < count; i++) {
									var selNode = dataView.getSelectedNodes()[i];
									new Ext.Window({
										title: selNode.id,
										autoScroll: true,
										//										layout: 'fit',
										width: 640,
										height: 480,
										plain: true,
										html: "<img src='HandlerGetPicture?id=" + selNode.lang + "'></img>"

									}).show();
								}



							}
						}, {
							text: _PictureResource_DeletePicture,
							iconCls: 'remove-icon',
							handler: function() {
								var count = dataView.getSelectionCount();
								var nodes = "";
								for (var i = 0; i < count; i++) {
									if (i == 0)
										nodes += dataView.getSelectedNodes()[0].lang
									else
										nodes += "," + dataView.getSelectedNodes()[i].lang;
								}

								Ext.Msg.show({ title: _PictureResource_Tips, msg: _PictureResource_DeleteTips,
									buttons: {
										yes: _PictureResource_Yes,
										no: _PictureResource_No
									},
									fn: function(button) {
										if (button == "yes") {
											Ext.MessageBox.show({
												msg: _PictureResource_Deleting + "...",
												progress: true,
												progressText: _PictureResource_Deleting + '...',
												width: 300,
												wait: true,
												waitConfig: {
													interval: 100,
													duration: 1000,
													fn: function() {
														Ext.Ajax.request({
															url: "HandlerDeletePictures",
															params: {
																ids: nodes
															},
															callback: function(options, success, response) {
																if (success) {
																	Ext.Msg.show({
																		title: _PictureResource_Tips,
																		msg: _PictureResource_DeleteSuccess,
																		buttons: Ext.MessageBox.OK,
																		icon: Ext.MessageBox.INFO,
																		fn: function() {
																			mystore.reload();
																		}
																	});
																}
																else {
																	Ext.Msg.show({
																		title: _PictureResource_Tips,
																		msg: _PictureResource_Deletefailed,
																		buttons: Ext.MessageBox.OK,
																		icon: Ext.MessageBox.WARNING
																	});
																}
															}
														});

														Ext.MessageBox.hide();
													}
												},
												closable: true
											});
										}
									}
								});
							}
}]
						});



					}

					dataView.menu.showAt(e.getXY());

					e.stopEvent();

				},
				onLoadException: function(v, o) {
					this.view.getEl().update('<div style="padding:10px;">' + _PictureResource_Error + '</div>');
				}
			};

			String.prototype.ellipse = function(maxLength) {
				if (this.length > maxLength) {
					return this.substr(0, maxLength - 3) + '...';
				}
				return this;
			};
			result = new ImageChooser({
				url: 'HandlerGetPicturesList',
				width: 1250,
				height: 480
			});
			return result

		}